﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;

namespace xuptlibsearch
{
    public partial class _default : System.Web.UI.Page
    {
        private List<BookList> BookInfo = new List<BookList>();

        string word = "";
        string cpage = "1";
        string kind = "simple";
        string type = "title";
        string match = "mh";
        string record = "01";
        string lib = "all";
        string size = "20";
        string orderby = "title";
        string ordersc = "asc";

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Charset = "UTF-8";
            Response.ContentType = "text/json";
            word = Request.Form["word"];
            //word = Server.UrlEncode(Request.Form["word"]);
            if (Request.Form["page"] != "" && Request.Form["page"] != null)
                cpage = Request.Form["page"];
            if (Request.Form["record"] != "" && Request.Form["record"] != null)
                record = Request.Form["record"];
            if (Request.Form["type"] != "" && Request.Form["type"] != null)
                type = Request.Form["type"];
            if (Request.Form["match"] != "" && Request.Form["match"] != null)
                match = Request.Form["match"];
            if (Request.Form["lib"] != "" && Request.Form["lib"] != null)
                lib = Request.Form["lib"];
            if (Request.Form["size"] != "" && Request.Form["size"] != null)
                size = Request.Form["size"];
            if (Request.Form["orderby"] != "" && Request.Form["orderby"] != null)
                orderby = Request.Form["orderby"];
            if (Request.Form["ordersc"] != "" && Request.Form["ordersc"] != null)
                ordersc = Request.Form["ordersc"];
            
            if (word == null || word == "")
            {
                Response.Write("Param_Error");
                return;
            }
            if (word.Length <= 1)
            {
                Response.Write("Keyword_Too_Short");
                return;
            }
            word = word.Replace("%", "%25");
            word = word.Replace("+", "%2b");
            word = word.Replace("?", "%3f");
            word = word.Replace("/", "%2f");
            word = word.Replace("&", "%26");
            word = word.Replace("=", "%3d");
            word = word.Replace(" ", "%20");
            word = word.Replace("#", "%23");
            try
            {
                info.Size = Convert.ToInt32(size);
            }
            catch
            {
                size = "20";
                info.Size = 20;
            }
            Getrequest();
        }
        BookInfo info = new xuptlibsearch.BookInfo();
        private void Getrequest()
        {
            if (word == "" || word == null)
            {
                Response.Write("Param_Error");
                return;
            }
            string str = "";
            string param = string.Format(
                "kind={0}&type={1}&word={2}&match={3}&recordtype={4}&library_id={5}&x=0&y=0&curpage={6}&size={7}&orderby={8}&ordersc={9}",
                kind, type, word, match, record, lib,cpage,size,orderby,ordersc);
            byte[] postBin = Encoding.GetEncoding("gb2312").GetBytes(param);
            try
            {
                string uri = "http://222.24.3.7:8080/book/queryOut.jsp";
                WebRequest request = WebRequest.Create(uri);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = postBin.Length;
                request.Timeout = 30000;
                Stream istream = request.GetRequestStream();
                istream.Write(postBin, 0, postBin.Length);
                WebResponse req= request.GetResponse();
                Stream stream = req.GetResponseStream();
                StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("gb2312"));
                str = reader.ReadToEnd();
            }
            catch
            {
                Response.Write("Server_Error");
                return;
            }

            if (str.Contains("没有检索到你想要的记录"))
            {
                Response.Write("null");
                return;
            }

            string amount = str.Substring(str.IndexOf("检索结果"));
            string sdsd = amount.Substring(amount.IndexOf("条"));
            amount = amount.Replace(sdsd, "");
            amount = amount.Replace("</span>", "");
            amount = amount.Replace("检索结果 ——\r\n\t\t\t\t\t共 <span class=\"opac_red\">", "");
            amount = amount.Replace(" ","");

            string page = str.Substring(str.IndexOf("页/共"));
            string tttt=page.Substring(page.IndexOf("</b>"));
            page = page.Replace(tttt, "");
            page = page.Replace("页/共<span class=\"opac_red\"> <b>", "");
            
            if (Convert.ToInt32(cpage) > Convert.ToInt32(page))
            {
                Response.Write("Out_Of_Range");
                return;
            }
            try
            {
                str = str.Replace("\r", "");
                str = str.Replace("\n", "");
                str = str.Replace("\t", "");
                str = str.Substring(str.IndexOf("<!--<td class=opac_white width=3% noWrap>下载</td>-->"));
                str = str.Substring(58);
                //str = str.Replace(" ", "");
                string tmp = str.Substring(str.IndexOf("</table></form>"));
                str = str.Replace(tmp, "");
                str = str.Replace("bgcolor=#EBF0F2", "");

                string[] result = Regex.Split(str, "</tr>");


                for (int i = 0; i < result.Length - 1; i++)
                {
                    string tt = result[i].Replace("<tr>", "");
                    tt = tt.Replace("<td>", "");
                    tt = tt.Replace("<tdalign=center>", "");
                    string[] d = Regex.Split(tt, "</td>");
                    string ssdf = d[1].Substring(d[1].IndexOf(")") + 1);
                    string a = d[1].Substring(d[1].IndexOf("("));
                    string[] num = Regex.Split(a.Replace(ssdf, "").Replace("(", "").Replace(")", "").Replace("'", ""), ",");
                    string ttt = d[1].Substring(1, d[1].Length - 5);

                    string isbn;
                    try
                    {
                        string[] isbnarray = Regex.Split(d[4].Replace("&nbsp;", ""), ",");
                        if (isbnarray.Length == 1)
                            isbn = d[4].Replace("&nbsp;", "").Replace("-", "");
                        else
                            isbn = isbnarray[0].Replace("-", "");
                        if (d[4].Replace("&nbsp;", "") == "不详")
                            isbn = null;
                    }
                    catch
                    {
                        isbn = null;
                    }

                    string id = num[1];
                    string title = ttt.Substring(ttt.IndexOf(">") + 1);
                    string author = d[2].Replace("&nbsp;", "");
                    if (Convert.ToInt32(amount) == 1)
                    {
                        author = author.Substring(author.IndexOf("</Script>") + 9);
                    }
                    string pub = d[3].Replace("&nbsp;", "");
                    string year = d[5].Replace("&nbsp;", "");
                    if(author!="" && author[author.Length-1]==',')
                    {
                        author=author.Substring(0,author.Length-1);
                    }
                    BookInfo.Add(new BookList
                    {
                        ID = id,
                        Name = title.Trim(),
                        Author = author.Trim(),
                        Pub = pub.Trim(),
                        ISBN = isbn.Trim(),
                        Year = year.Trim()
                    });
                }
            }
            catch
            {
                Response.Write("Process_Error");
                return;
            }
            
            info.Amount = Convert.ToInt32(amount);
            info.Pages = Convert.ToInt32(page);
            info.CurrentPage = Convert.ToInt32(cpage);
            info.BookData = BookInfo;
            JavaScriptSerializer jsonstr = new JavaScriptSerializer();
            Response.Write(jsonstr.Serialize(info));
            return;
        }
    }
    public class BookInfo
    {
        public int Amount
        {
            get;
            set;
        }
        public int CurrentPage
        {
            get;
            set;
        }
        public int Pages
        {
            get;
            set;
        }
        public int Size
        {
            get;
            set;
        }
        public List<BookList> BookData
        {
            get;
            set;
        }
    }
}